import Config from './config.js'
import { getToken, setToken, removeToken, refreshToken } from '@/common/auth'
async function upload(option) 
{
	if (option.urlname) {
		option.url  = Config.url[option.urlname]
	}
	option.header = {
		// 'Content-Type':'application/x-www-form-urlencoded',
	}
	//过期，即先拦截 ，刷新token后，再继续请求
	//authorizations/current
	var token = getToken();
	var tmpToken = await refreshToken();
	if(tmpToken){
		token = tmpToken;
	}
	// console.log('token : ', token)
	if(token){
		option.header['Authorization'] = 'Bearer ' + token;
	}
	var succ_callback = option.success;
	option.success = function(res){
		var res = JSON.parse(res.data);
		console.log('upload ', res)
		if(res.statusCode && res.statusCode >= 400){
			console.log('request error statusCode', res.statusCode, res);
			if(Config.show_err){
				uni.showModal({
					title: '异常', 
				    content: ''+res.data.message,
					showCancel: false
				});
			}
			//正常显示
			if(res.data.message){
				uni.showModal({
					title: Config.common_text.request_err, 
				    content: ''+res.message,
					showCancel: false
				});
			}
			
			if(! token){
				var pages = getCurrentPages();
				var route = (pages[pages.length - 1]).route;
				if(route == 'pages/public/login'){
					return false;
				}
				uni.showModal({
				    content: Config.common_text.login_expired,
					showCancel: false,
					success: function(res){
						uni.navigateTo({
							url: `/pages/public/login`
						})
					}
				});
			}
			
			return false;
		}
		succ_callback(res);
	}
	uni.uploadFile(option);
	
}
export default upload